import { jiweiAxios } from "../axios.js";
import {
  commonUtil,
  inputUtils,
  loginUtil,
  IDCardUtils,
} from "../../../utils/index.js";
import { documentCommonAdapter } from "../adapter/common/document.js";
import { DICT, STATUS, URL, CONFIG } from "../config.js";
import { getBaseParam, checkAnnualExisted } from "../jiweiUtils.js";
import {
  checkExitedParams,
  addDocumentParams,
  deleteDocumentParams,
} from "./params.js";
import cloneDeep from "lodash/cloneDeep.js";
import cheerio from "cheerio";
import iconv from "iconv-lite";
import pick from "lodash/pick.js";

const { DOCUMENT_DICT, DOCUMENT_DICT_INVERT } = commonUtil.getInvertDict(
  DICT,
  "DOCUMENT_DICT"
);
const { setPersonStatusAndNote } = commonUtil;
const main = async () => {
  const res = await commonUtil.confirmContinue(
    `现在是${CONFIG.IS_DOCUMENT_CHECK_EXISTED ? "查询" : "录入"}模式` +
      `${
        !CONFIG.IS_DOCUMENT_CHECK_EXISTED && CONFIG.IS_DELETE_DOCUMENT
          ? "会删除原有档案再录入"
          : "遇到存在档案会跳过"
      } `
  );
  console.log(res);
  const excelName = await commonUtil.selectExcel();
  const personList = commonUtil.excelToJson(excelName, DOCUMENT_DICT_INVERT);
  await inputUtils.input({
    dataList: personList,
    fn: input,
    loginFn: loginUtil.panyuJiweiLogin,
    DICT: DOCUMENT_DICT,
    excelName,
  });
};

async function input(person) {
  const { BASE_PARAM1 } = await getBaseParam();

  person.IDNum = IDCardUtils.formatIDNum(person.IDNum);
  if (!IDCardUtils.verifyIDNum(person.IDNum)) {
    return setPersonStatusAndNote(person, STATUS.WRONG, "身份证输入有误");
  }


  const originPerson = { ...person };
  // 不是查询模式的时候才需要格式化
  if (!CONFIG.IS_DOCUMENT_CHECK_EXISTED) {
    person = documentCommonAdapter(person);
  }

  if (person.STATUS) {
    return { ...originPerson, STATUS: person.STATUS, NOTE: person.NOTE };
  }

  const { isExisted: isAnnualExisted } = await checkAnnualExisted({
    person,
    BASE_PARAM1,
  });

  if (isAnnualExisted && !CONFIG.IS_DELETE_DOCUMENT) {
    return setPersonStatusAndNote(originPerson, STATUS.EXISTED, person.NOTE);
  }
  const {
    isUs,
    isExisted: isDocumentExisted,
    $CHECK_EXISTED2,
  } = await checkExisted(person.IDNum);
  if (!isUs) {
    return setPersonStatusAndNote(originPerson, STATUS.NOT_US, person.NOTE);
  }

  if (isDocumentExisted && !CONFIG.IS_DELETE_DOCUMENT) {
    return setPersonStatusAndNote(originPerson, STATUS.NOT_US, person.NOTE);
  }

  if (isDocumentExisted && CONFIG.IS_DELETE_DOCUMENT) {
    const res = await deleteDoc(person, $CHECK_EXISTED2);
    if (res?.STATUS) return { ...originPerson, ...res };
  }
  if (CONFIG.IS_DOCUMENT_CHECK_EXISTED) {
    return setPersonStatusAndNote(originPerson, STATUS.NOT_BUILD);
  }

  person = await addDocument(person);
  return commonUtil.setPersonStatusAndNote(originPerson, person.STATUS, person.NOTE);
}

async function checkExisted(IDNum) {
  const RES = await jiweiAxios({
    url: URL.DOCUMENT_CHECK_EXISTED,
    responseType: "arraybuffer",
  });
  const HTML = iconv.decode(RES.data, "gb2312");
  const $CHECK_EXISTED = cheerio.load(HTML);

  let params = cloneDeep(checkExitedParams);
  params = {
    ...params,
    __VIEWSTATE: $CHECK_EXISTED("#__VIEWSTATE").attr("value"),
    txtRecod: IDNum,
    hdnQueryString: `IDCARDNO/${IDNum}/////1//`,
    hdnCurrentZoneID: $CHECK_EXISTED("#hdnCurrentZoneID").attr("value"),
    hdnZoneName: $CHECK_EXISTED("#hdnZoneName").attr("value"),
    hdnOrgID: $CHECK_EXISTED("#hdnOrgID").attr("value"),
    hdnLoginZoneID: $CHECK_EXISTED("#hdnLoginZoneID").attr("value"),
    hdnLoginOrgID: $CHECK_EXISTED("#hdnLoginOrgID").attr("value"),
    hdnStartAge: $CHECK_EXISTED("#hdnStartAge").attr("value"),
    hdnEndAge: $CHECK_EXISTED("#hdnEndAge").attr("value"),
    hdnFrm: $CHECK_EXISTED("#hdnFrm").attr("value"),
    __VIEWSTATEGENERATOR: $CHECK_EXISTED("#__VIEWSTATEGENERATOR").attr("value"),
    __EVENTVALIDATION: $CHECK_EXISTED("#__EVENTVALIDATION").attr("value"),
  };

  const RES2 = await jiweiAxios({
    method: "post",
    data: commonUtil.jsonToGBKURLString(params),
    url: URL.DOCUMENT_CHECK_EXISTED,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    responseType: "arraybuffer",
  });
  const HTML2 = iconv.decode(RES2.data, "gb2312");
  const $CHECK_EXISTED2 = cheerio.load(HTML2);

  // commonUtil.writeToFile(HTML2, { fileType: "html" });
  return {
    isUs:
      $CHECK_EXISTED2(
        "#tableNeirong > tbody > tr:nth-child(3) > td > a:last-child"
      ).attr("style") !== "display:none",
    isExisted: $CHECK_EXISTED2("#trQueryNone td").text() !== "查无记录!",
    $CHECK_EXISTED2,
  };
}

async function addDocument(person) {
  // 新增模式
  const RES1 = await jiweiAxios({
    url: URL.DOCUMENT,
    responseType: "arraybuffer",
    params: {
      FromType: 1,
    },
  });

  const HTML1 = iconv.decode(RES1.data, "gb2312");
  if (HTML1.includes("非此档案的管理机构或者服务机构，不可修改！")) {
    person.NOTE = "档案非本机构创建，无法修改";
    return STATUS.WRONG;
  }
  const $HTML1 = cheerio.load(HTML1);

  // 新增模式需要一个recordNo
  const url = $HTML1(
    'script[src^="/pyjw/ajaxpro/HR_PersonRecord_AspCode_PersonRecord_PersonRecord_Detail,App_Web_"]'
  )
    .first()
    .attr("src")
    .replace("/pyjw", "");
  const res = await jiweiAxios({
    url,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Ajax-method": "GetRecordNo",
    },
    data: `{"Regzone": "${person.NowAddress$hdnZone.replace(
      /\d{3}$/,
      "000"
    )}"}`,
  });
  let RECORD_NO = res.data;

  const data2 = {
    ...addDocumentParams,
    __VIEWSTATE: $HTML1("#__VIEWSTATE").val(),
    HEALTHDOCNO: RECORD_NO,
    hid_Personname: $HTML1("#hid_Personname").val() || "",
    hid_Perrecordid: $HTML1("#hid_Perrecordid").val() || "",
    NAME: person.NAME || $HTML1("#NAME").val() || "",
    CreatePerson:
      person.CreatePerson ||
      $HTML1("#CreatePerson").val() ||
      $HTML1("#CreatePerson").text() ||
      $HTML1("#CREATEUSERNAME").text(),
    DutyDoctor: person.DutyDoctor || $HTML1("#CreatePerson").val(), // 责任医生
    hdallgms: $HTML1("#hdallgms").val() || "",
    hdallbls: $HTML1("#hdallbls").val() || "",
    hdallbs: $HTML1("#hdallbs").val() || "",
    hdallsss: $HTML1("#hdallsss").val() ?? "",
    // rbtnlistws: person.rbtnlistws,
    hdallwss: $HTML1("#hdallwss").val() ?? "",
    // rbtnlistsx: person.rbtnlistsx,
    hdallsxs: $HTML1("#hdallsxs").val() ?? "",
    hdallyc: $HTML1("#hdallyc").val(),
    hdallcjs: $HTML1("#hdallcjs").val(),
    ORG: $HTML1("#ORG").val(),
    hddep: $HTML1("#hddep").val(),
    hdadmin: $HTML1("#hdadmin").val(),
    hdnZoneFilter: `+@ZONE+>=+'${global.user.JiGou.substr(0, 6).padEnd(
      12,
      "0"
    )}'+and+@ZONE+<='${global.user.JiGou.substr(0, 6).padEnd(12, "9")}'+`, // +@ZONE+>=+'440113000000'+and+@ZONE+<='440113999999'+
    VS_RECORDNO: RECORD_NO,
    __VIEWSTATEGENERATOR: $HTML1("#__VIEWSTATEGENERATOR").val(),
    __VIEWSTATEENCRYPTED: "",
    __EVENTVALIDATION: $HTML1("#__EVENTVALIDATION").val(),
    ...person,
  };

  const RES2 = await jiweiAxios({
    url: URL.DOCUMENT,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Connection: "Keep-Alive",
      "User-Agent":
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)",
    },
    data: commonUtil.jsonToGBKURLString(
      commonUtil.setUndefinedValueToEmptyString(
        pick(
          data2,
          Object.keys(data2).filter((item) => /^[_$\w]*$/.test(item))
        )
      )
    ),
    params: {
      1: 1,
      FromType: 1,
    },
    responseType: "arraybuffer",
  });
  const HTML2 = iconv.decode(RES2.data, "gb2312");
  if (~HTML2.indexOf("存在一条相同的记录")) {
    person.STATUS = STATUS.FINISH;
    // person.NOTE = '存在一条相同的记录';
    return person;
  } else if (~HTML2.indexOf("个人档案登记")) {
    if (HTML2.includes("现住地址不允许选择")) {
      person.NOTE = "现住址不能选择本社区外的地址";
      person.STATUS = STATUS.WRONG;
      return person;
    } else if (HTML2.includes("个人档案更新失败")) {
      person.NOTE = "档案非本社区无法修改或其他原因";
      person.STATUS = STATUS.WRONG;
      return person;
    }
    person.STATUS = STATUS.FINISH;
    return person;
  } else {
    person.STATUS = STATUS.WRONG;
    person.NOTE = "未知错误，请核对excel数据格式";
    return person;
  }
}

async function deleteDoc(person, $existed) {
  const [, hdnRecordNo, hdnPerrecordID, , , hdnRecord] = $existed(
    '[onclick^="ShowFormOfLinkOthers"]'
  )
    .attr("onclick")
    .match(/\((.*)\)/)[1]
    .replace(/'/g, "")
    .split(",");

  const data = {
    ...deleteDocumentParams,
    __VIEWSTATE: $existed("#__VIEWSTATE").val(),
    txtRecod: person.IDNum,
    hdnPerrecordID,
    hdnRecordNo,
    hdnRecord,
    hdnFrm: $existed("#hdnFrm").val(),
    __VIEWSTATEGENERATOR: $existed("#__VIEWSTATEGENERATOR").val(),
    __EVENTVALIDATION: $existed("#__EVENTVALIDATION").val(),
  };

  try {
    const RES = await jiweiAxios({
      url: URL.DOCUMENT_CHECK_EXISTED,
      method: "post",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      data: commonUtil.jsonToGBKURLString(data),
      responseType: "arraybuffer",
    });
    const HTML = iconv.decode(RES.data, "gb2312");
    const $HTML = cheerio.load(HTML);

    if ($HTML("#trQueryNone td").text() !== "查无记录!") {
      return { STATUE: STATUS.WRONG, NOTE: "删除失败，请联系开发者排查" };
    }
  } catch (error) {
    return { STATUS: STATUS.WRONG, NOTE: `删除失败：${error}` };
  }
}

export default main;
